<template>
  <div class="layout-wrapper layout-witness">
    <div class="layout-header layout-search">
      <el-form :inline="true">
        <el-form-item>
          <el-button type="primary" @click="addDate()"> 新增 </el-button>
        </el-form-item>
        <el-button class="float-right" type="text" icon="el-icon-back" @click="handleBackFn">返回&nbsp;&nbsp;&nbsp;&nbsp;</el-button>
      </el-form>
    </div>
    <div class="layout-body">
      <el-table ref="taskTable" v-loading="tableLoading" :data="tableData" height="100%" stripe>
        <el-table-column type="index" align="left" label="序号" width="50">
          <template slot-scope="scope">
            {{ pageObj.currentPage * pageObj.pageSize + 1 + scope.$index }}
          </template>
        </el-table-column>
        <el-table-column prop="username" label="姓名" min-width="120" />
        <el-table-column prop="ssdw" label="所属单位" min-width="180" />
        <el-table-column prop="idcard" label="身份证号" min-width="130" />
        <el-table-column prop="mobile" label="手机号" min-width="130" />
        <el-table-column label="操作" align="left" header-align="center" width="140">
          <template slot-scope="scope">
            <!--            <el-button type="text" size="default" @click="viewDate(scope.row)"> 查看 </el-button>-->
            <el-button type="text" size="default" @click="updateDate(scope.row)"> 修改 </el-button>
            <el-button type="text" size="default" @click="deleteUserManager(scope.row.id)"> 删除 </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="layout-footer">
      <wpagination
        v-if="pageObj.total > pageObj.pageSizes[0]"
        :total="pageObj.total"
        :page.sync="pageObj.currentPage"
        :limit.sync="pageObj.pageSize"
        :pageSizes="pageObj.pageSizes"
        @pagination="projectListFn()"
      />
    </div>
    <!-- 编辑弹框 -->
    <el-dialog
      width="60%"
      :close-on-click-modal="false"
      draggable
      :show-close="false"
      title="人员信息"
      :visible.sync="editTempl"
    >
      <div>
        <el-form ref="templForm" :model="templForm" :rules="templRules" label-width="auto">
          <el-form-item label="姓名" prop="username">
            <el-input
              v-model="templForm.username"
              placeholder="请输入姓名"
              :disabled="childType == 'view' ? true : false"
            />
          </el-form-item>
          <el-form-item label="所属单位" prop="ssdw">
            <el-input
              v-model="templForm.ssdw"
              placeholder="请输入所属单位"
              :disabled="childType == 'view' ? true : false"
            />
          </el-form-item>
          <el-form-item label="身份证号码" prop="idcard">
            <el-input
              v-model="templForm.idcard"
              placeholder="请输入身份证号码"
              :disabled="childType == 'view' ? true : false"
            />
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input
              v-model="templForm.mobile"
              placeholder="请输入手机号"
              :disabled="childType == 'view' ? true : false"
            />
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="childType != 'view'" :loading="btnLoading" type="primary" @click="submitData('templForm')"
        >确定</el-button
        >
        <el-button @click="cancel('templForm')">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
import { templPage, templAdd, templDelete } from "../../../../../../api/weeon/task/gly/userManager";
export default {
  // 引入组件
  components: {},
  props: {},
  data() {
    // 这里存放数据
    return {
      bdguid: "",
      childType: "",
      editTempl: false,
      btnLoading: false,
      roomDeviceShow: false,
      tableData: [],
      tableLoading: false,
      pageObj: {
        total: 0,
        currentPage: 0,
        pageSize: 10,
        pageSizes: [10, 20, 30]
      },
      templForm: {
        username:"",
        ssdw:"",
        idcard:"",
        mobile:"",
        bdguid:"",
        type:"GZRY",
      },
      templRules: {
        username: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        ssdw: [{ required: true, message: "请输入所属单位", trigger: "blur" }],
        idcard: [{ required: true, message: "请输入身份证号码", trigger: "blur" },{ pattern:/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,message: "请输入正确的身份证号码"}],
        mobile:[{ required: true, message: "请输入手机号", trigger: "blur" },{ pattern: /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/,message: "请输入正确的手机号"}]
      }
    };
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.projectListFn();
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    let bdguid = this.$route.query.bdguid;
    this.bdguid = bdguid;
    this.templForm.bdguid = bdguid;
  },
  // 生命周期 - 销毁之前
  beforeDestroy() {},
  // 生命周期 - 销毁完成
  destroyed() {},
  // 如果页面有keep-alive缓存功能，这个函数会触发
  activated() {},
  // 方法集合
  methods: {
    handleBackFn() {
      this.$router.push({ path: "/taskManager"});
    },
    // 搜索查询
    handleSearchFn() {
      this.pageObj.total = 0;
      this.pageObj.currentPage = 0;
      this.projectListFn();
    },
    // 数据列表
    async projectListFn() {
      try {
        this.tableLoading = true;
        this.tableData = [];
        console.log()
        let params = {
          pageNo: this.pageObj.currentPage,
          pageSize: this.pageObj.pageSize,
          bdguid: this.$route.query.bdguid,
          type: "GZRY",
        };
        const res = await templPage(params);
        if (res.stat === 1) {
          if (res.data.totalElements === 0 && this.pageObj.currentPage !== 0) {
            this.pageObj.currentPage = 0;
            this.$nextTick(() => {
              this.projectListFn();
            });
            return;
          }

          this.tableData = res.data.content;
          console.log(this.tableData, "-------------------1");
          this.pageObj.total = res.data.totalElements;
          this.tableLoading = false;
        } else {
          this.tableLoading = false;
          this.$message({
            type: "error",
            message: res.msg || "获取数据失败，请稍后再试",
            single: true
          });
        }
      } catch (error) {
        console.log(error);
        this.tableLoading = false;
      }
    },

    //新增操作
    addDate() {
      this.editTempl = true;
      this.childType = "edit";
    },//修改操作
    updateDate(row) {
      this.editTempl = true;
      this.templForm = row;
      this.childType = "edit";
    },
    //取消
    cancel(formName) {
      this.editTempl = false;
      this.childType = "";
      this.tableLoading = false;
      this.btnLoading = false;
      this.templForm ={};
      this.$refs[formName].resetFields();
      this.projectListFn();
      // this.roomDeviceShow = false;
    },
    //保存修改
    submitData(formName) {
      let this_ = this;
      try {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.doAdd();
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      } catch (error) {
        console.error(error);
        this.$message({
          type: "warning",
          message: "保存数据失败，稍后再试"
        });
      }
    },
    //保存
    async doAdd() {
      this.btnLoading = true;
      const res = await templAdd(this.templForm);
      if (res.stat === 1) {
        this.$message({
          type: "success",
          message: "保存成功",
          single: true
        });
      } else {
        this.$message({
          type: "warning",
          message: res.msg,
          single: true
        });
      }
      this.btnLoading = false;
      this.editTempl = false;
      this.childType = "";
      this.$refs.templForm.resetFields(); //清空对象
      this.projectListFn(); //刷新列表
    },
    //格式化设备类型
    formatterTemplType(row, col, val){
      let str = "";
      if (val) {
        str = this.templtype[val];
      }
      return str;
    },
    //是否启用
    formatterDeviceenable(row, col, val) {
      console.log(val);
      let str = "是";
      if (val === "0") {
        str = "否";
      }
      return str;
    },
    //修改设备状态
    deleteUserManager(id){
      this.$confirm("确定删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.deleteUser(id);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消操作",
            single: true
          });
        });
    },
    async deleteUser(id){
      try {
        this.tableLoading = true;
        const res = await templDelete({id: id});
        this.tableLoading = false;
        if (res.stat === 1) {
          this.$message({
            type: "success",
            message: "操作成功",
            single: true
          });
          this.projectListFn();
        } else {
          this.$message({
            type: "error",
            message: res.msg || "操作失败",
            single: true
          });
        }
      } catch (error) {
        console.error(error);
        this.tableLoading = false;
      }
    },
  }
};
</script>
<style lang="scss" scoped>
.witness-result {
  width: 76px;
  height: 20px;
  line-height: 20px;
  background: #fc9306;
  border-radius: 10px;
  color: #fff;
  font-size: 12px;
  text-align: center;
}
.rigthText {
  padding-right: 10px;
  float: right;
  // margin-left: 460px !important;
}
.colorRed {
  color:red;
}
</style>
